<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>遗产档案系统管理</a-breadcrumb-item>
      <a-breadcrumb-item>遗产区划分区管理</a-breadcrumb-item>
    </a-breadcrumb>
    <a-tabs>
      <a-tab-pane key="1" tab="列表管理">
        <a-row>
          <a-col :span="6">
            遗产分区：
            <a-input placeholder="请输入" v-model="query.heritageZone" />
          </a-col>
          <a-col :span="18">
            <a-button type="primary" @click="getQuery"> 查询 </a-button>
          </a-col>
          <a-col :span="4">查询表单</a-col>
          <a-col :span="18"></a-col>
          <a-col :span="2">
            <a-button
              type="primary"
              @click="openaddMap"
              v-hasPermi="['yichan:ycqhfqg:add']"
            >
              新建
            </a-button>
          </a-col>
          <a-col :span="24">
            <a-table
              :columns="columns"
              :data-source="data"
              :rowKey="
                (record, index) => {
                  return index;
                }
              "
              :pagination="false"
            >
              <span slot="action" slot-scope="text, record">
                <a
                  @click="changeData(record)"
                  v-hasPermi="['yichan:ycqhfqg:edit']"
                  >编辑</a
                >
                <a-divider type="vertical" />

                <a-popconfirm
                  placement="left"
                  title="您正在进行删除操作，删除后数据不可恢复，确定删除吗？"
                  ok-text="确认"
                  cancel-text="取消"
                  class="red"
                  @confirm="deleteData(record)"
                  v-hasPermi="['yichan:ycqhfqg:del']"
                >
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </a-table>
            <a-locale-provider :locale="$zhCN">
              <a-pagination
                style="float: right; margin-top: 10px"
                v-model="query.current"
                show-size-changer
                :total="total"
                :page-size-options="pageSizeOptions"
                :page-size="query.pageSize"
                @change="pageChange"
                @showSizeChange="pageSizeChange"
                :show-total="(total) => `共 ${total} 条`"
              />
            </a-locale-provider>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="2" tab="地图查看">
        <a-row>
          <a-col span:20></a-col>
          <a-col span:4>
            <a-button
              type="primary"
              @click="openaddMap()"
              v-hasPermi="['yichan:ycqhfqg:add']"
            >
              新建
            </a-button>
          </a-col>
          <a-col span:24>
            <div class="mapDiv">
              <tdt-map :center="center2" :zoom="zoom2">
                <tdt-polygon
                  v-for="(item, index) in polygonPath"
                  :key="index"
                  :path="item"
                  color="red"
                  :opacity="1"
                  :edit="false"
                ></tdt-polygon>
              </tdt-map>
            </div>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
    <a-modal
      v-model="vis"
      width="40%"
      title="修改区域"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleOk"
    >
      <a-row>
        <a-col :span="24">
          * 遗产分区：&emsp;&emsp;<a-input
            placeholder="请输入"
            v-model="newPic.heritageZone"
            style="width: 70%"
          />
        </a-col>
        <a-col :span="24">
          * 片区管理人员：<a-cascader
            v-model="newPic.manager"
            style="width: 70%"
            :options="fzroptions"
            :load-data="loadData"
            placeholder="请选择"
            change-on-select
            @change="selectFzr"
          />
        </a-col>
        <a-col :span="24">
          * 区域经纬度点：<a-input
            placeholder="请输入"
            v-model="newPic.coordinates"
            style="width: 70%"
          />
        </a-col>
      </a-row>
    </a-modal>
    <a-modal
      v-model="vis1"
      width="40%"
      title="新增区域"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleOk1"
    >
      <a-row>
        <a-col :span="24">
          * 遗产分区：&emsp;&emsp;<a-input
            placeholder="请输入"
            v-model="newPic.heritageZone"
            style="width: 70%"
          />
        </a-col>
        <a-col :span="24">
          * 片区管理人员：<a-cascader
            style="width: 70%"
            :options="fzroptions"
            :load-data="loadData"
            placeholder="请选择"
            v-model="newPic.manager"
            change-on-select
            @change="selectFzr"
          />
        </a-col>
        <a-col :span="24">
          * 区域经纬度点：<a-input
            placeholder="请输入"
            v-model="newPic.coordinates"
            style="width: 70%"
          />
          <br />
        </a-col>
        <a-col :span="24">
          <a-button type="primary" @click="openTool('polygonTool')">
            自定义图形
          </a-button>
          <a-button
            style="margin-left: 10px"
            type="primary"
            @click="clearTool()"
          >
            清除
          </a-button>
        </a-col>
        <a-col :span="24">
          <div class="mapDiv">
            <tdt-map :center="center" :zoom="13">
              <tdt-mousetool
                ref="mousetoolRef"
                :markTool="{ follow: true }"
                @mark-mouseup="onMarkMouseup"
                @polygon-draw="onMarkMouseup1"
              >
              </tdt-mousetool>
              <tdt-polygon
                v-for="(item, index) in dialogPolygonPath"
                :key="index"
                :path="item"
                color="red"
                :opacity="1"
                :edit="false"
              ></tdt-polygon>
            </tdt-map>
          </div>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
const columns = [
  {
    title: "序号",
    dataIndex: "id",
    key: "id",
  },
  {
    title: "遗产分区",
    dataIndex: "heritageZone",
    key: "heritageZone",
  },
  {
    title: "区域经纬度点",
    dataIndex: "coordinates",
    key: "coordinates",
    width: 800,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
  },
  {
    title: "片区管理人员",
    dataIndex: "manager",
    key: "manager",
    width: 120,
    customRender: (text) => {
      let itemOne = JSON.parse(text);
      if (itemOne.length == 3) {
        var item = itemOne[2].split("/**/");
        return item[1];
      } else {
        return "";
      }
    },
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    width: 100,
  },
];
export default {
  mounted() {
    this.getList();
  },
  data() {
    return {
      button: [],
      data: [],
      columns,
      vis: false,
      vis1: false,
      pageSizeOptions: ["10", "20", "50"],
      total: 0,
      query: {
        current: 1,
        pageSize: 10,
        heritageZone: "",
      },
      fzroptions: [],
      newPic: {
        heritageZone: "",
        coordinates: [],
        manager: "",
      },
      center: [100.236607, 26.864888],
      zoom: 14,
      center2: [100.236607, 26.875],
      zoom2: 15,
      polygonPath: [],
      dialogPolygonPath:[],
    };
  },

  methods: {
    openTool(toolName) {
      this.$refs.mousetoolRef.open(toolName);
    },
    clearTool(toolName) {
      toolName
        ? this.$refs.mousetoolRef.clear(toolName)
        : this.$refs.mousetoolRef.clearAll();
      this.newPic.coordinates = [];
    },
    onMarkMouseup(polygonToolEvent) {},
    onMarkMouseup1(e) {
      if (
        e &&
        e.type == "draw" &&
        e.currentLnglats &&
        Array.isArray(e.currentLnglats)
      ) {
        this.newPic.coordinates = [];
        for (let i = 0; i < e.currentLnglats.length; i++) {
          if (
            e.currentLnglats[i] &&
            e.currentLnglats[i].lng &&
            e.currentLnglats[i].lat
          ) {
            this.newPic.coordinates.push([
              "E:" + e.currentLnglats[i].lng,
              "N:" + e.currentLnglats[i].lat,
            ]);
          }
        }
      }
    },
    getQuery() {
      this.query.offset = 1;
      this.getList();
    },
    cleanQuery() {
      this.query = {
        current: 1,
        pageSize: 10,
        heritageZone: "",
      };
    },
    getList() {
      var q = "government-platform-center/heritageZone";
      for (const prop in this.query) {
        if (this.query[prop] != "") {
          if (prop == "current") {
            q = q + "?offset=" + this.query[prop];
          } else if (prop == "pageSize") {
            q = q + "&current=" + this.query[prop];
          } else {
            q = q + "&" + prop + "=" + this.query[prop];
          }
        }
      }
      this.$axios
        .get(q)
        .then((res) => {
          if (res.data.msg == "success") {
            this.data = res.data.data;
            this.total = res.data.total;
            this.polygonPath = [];
            for (let i = 0; i < this.data.length; i++) {
              try {
                var lng = [];
                var lat = [];
                if (this.data[i].coordinates && typeof this.data[i].coordinates === 'string') {
                  var item = this.data[i].coordinates.split(",");
                  for (let j = 0; j < item.length; j++) {
                    if (item[j] && typeof item[j] === 'string') {
                      if (j % 2 === 0 && item[j].startsWith("E:")) {
                        lng.push(parseFloat(item[j].slice(2)));
                      } else if (item[j].startsWith("N:")) {
                        lat.push(parseFloat(item[j].slice(2)));
                      }
                    }
                  }
                  var arr = [];
                  for (let k = 0; k < lng.length; k++) {
                    if (!isNaN(lng[k]) && !isNaN(lat[k])) {
                      arr.push([lng[k], lat[k]]);
                    }
                  }
                  if (arr.length > 0) {
                    this.polygonPath.push(arr);
                  }
                }
              } catch (error) {
                console.error("处理坐标数据出错:", error);
              }
            }
          } else {
            this.$message.error(res.data.msg || "获取数据失败");
          }
        })
        .catch((err) => {
          this.$message.error("获取数据失败：" + (err.message || "未知错误"));
        });
      var q1 = "government-platform-center/dept?offset=1&current=100";
      this.$axios.get(q1).then((res) => {
        if (res.data.msg == "success") {
          var data = res.data.data;
          this.fzroptions = [];
          for (let i = 0; i < data.length; i++) {
            this.fzroptions.push({
              value: data[i].thisData.deptId,
              label: data[i].thisData.deptName,
              children: [],
            });
            for (let j = 0; j < data[i].childList.length; j++) {
              this.fzroptions[i].children.push({
                value: data[i].childList[j].thisData.deptId,
                label: data[i].childList[j].thisData.deptName,
                isLeaf: false,
              });
            }
          }
        }
      });
    },
    selectFzr(e) {
      if (e && e.length == 3) {
        var item = e[2].split("/**/");
        this.newPic.userId = item[0];
        this.newPic.manager = e;
      }
    },
    loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      var q =
        "/government-platform-center/dept/getUserListByDeptId?deptId=" +
        targetOption.value;
      this.$axios
        .get(q)
        .then((res) => {
          if (res.data.msg == "success") {
            targetOption.loading = false;
            targetOption.children = [];
            for (let i = 0; i < res.data.data.length; i++) {
              targetOption.children.push({
                label: res.data.data[i].userName,
                value:
                  res.data.data[i].userId + "/**/" + res.data.data[i].userName,
              });
            }
            this.fzroptions = [...this.fzroptions];
          } else {
            targetOption.loading = false;
            this.$message.error(res.data.msg || "加载数据失败");
          }
        })
        .catch((err) => {
          targetOption.loading = false;
          this.$message.error("加载数据失败：" + (err.message || "未知错误"));
        });
    },
    pageChange(current) {
      this.query.current = current;
      this.getList();
    },
    pageSizeChange(current, pageSize) {
      this.query.pageSize = pageSize;
      this.query.current = current;
      this.getList();
    },
    openaddMap() {
      this.newPic = {
        heritageZone: "",
        coordinates: [],
        manager: [],
        userId: "",
      };
      this.vis1 = true;
    },
    handleOk() {
      if (
        !this.newPic.heritageZone ||
        !this.newPic.coordinates ||
        !this.newPic.manager
      ) {
        this.$message.error("请完善所有必填项");
        return;
      }
      var parmas = { ...this.newPic };
      if (Array.isArray(parmas.manager)) {
        parmas.manager = JSON.stringify(parmas.manager);
      }
      this.$axios
        .post("/government-platform-center/heritageZone/edit", parmas, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          if (res.data.msg == "success") {
            this.$message.success("修改成功");
            this.getList();
            this.vis = false;
            this.newPic = {
              heritageZone: "",
              coordinates: [],
              manager: "",
              userId: "",
            };
          } else {
            this.$message.error(res.data.msg || "修改失败");
          }
        })
        .catch((err) => {
          this.$message.error("修改失败：" + (err.message || "未知错误"));
        });
    },
    handleOk1() {
      if (
        !this.newPic.heritageZone ||
        !this.newPic.coordinates ||
        !this.newPic.coordinates.length === 0 ||
        !this.newPic.manager
      ) {
        this.$message.error("请完善所有必填项");
        return;
      }

      var parmas = { ...this.newPic };
      if (Array.isArray(parmas.manager)) {
        parmas.manager = JSON.stringify(parmas.manager);
      }
      if (Array.isArray(parmas.coordinates)) {
        parmas.coordinates = parmas.coordinates.toString();
      }

      this.$axios
        .post("government-platform-center/heritageZone", parmas, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          if (res.data.msg == "success") {
            this.$message.success("新增成功");
            this.getList();
            this.vis1 = false;
            this.newPic = {
              heritageZone: "",
              coordinates: [],
              manager: "",
              userId: "",
            };
          } else {
            this.$message.error(res.data.msg || "新增失败");
          }
        })
        .catch((err) => {
          this.$message.error("新增失败：" + (err.message || "未知错误"));
        });
    },
    changeData(record) {
      this.newPic = { ...record };
      let manager = [];
      try {
        manager = JSON.parse(record.manager);
        this.newPic.manager = manager;
      } catch (e) {
        this.$message.error("管理人员数据格式错误");
        return;
      }

      if (manager && manager.length >= 2) {
        const [first, second] = manager;
        var q =
          "/government-platform-center/dept/getUserListByDeptId?deptId=" +
          manager[1];
        this.$axios.get(q).then((res) => {
          if (res.data.msg == "success") {
            // 递归遍历this.fzroptions，找到匹配first和second的节点
            const findAndUpdateOptions = (
              options,
              firstVal,
              secondVal,
              userData
            ) => {
              for (let i = 0; i < options.length; i++) {
                // 找到第一层匹配
                if (options[i].value === firstVal) {
                  // 在第一层的children中寻找匹配second的项
                  if (options[i].children && options[i].children.length > 0) {
                    for (let j = 0; j < options[i].children.length; j++) {
                      // 找到第二层匹配
                      if (options[i].children[j].value === secondVal) {
                        // 清空并更新children
                        options[i].children[j].children = [];
                        // 将API返回的数据填充到children中
                        for (let k = 0; k < userData.length; k++) {
                          options[i].children[j].children.push({
                            label: userData[k].userName,
                            value:
                              userData[k].userId +
                              "/**/" +
                              userData[k].userName,
                          });
                        }
                        return true; // 找到并更新成功
                      }
                    }
                  }
                }
              }
              return false; // 未找到匹配项
            };

            // 调用递归函数更新fzroptions
            findAndUpdateOptions(this.fzroptions, first, second, res.data.data);

            // 更新fzroptions以触发视图更新
            this.fzroptions = [...this.fzroptions];
          }
        });
      }
      this.vis = true;
    },
    deleteData(record) {
      var parmas = {
        id: record.id,
      };
      this.$axios
        .post("government-platform-center/heritageZone/deleteById", parmas, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          if (res.data.msg == "success") {
            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
  },
};
</script>
<style scoped>
.ant-row {
  border-radius: 5px;
  margin-bottom: 15px;
  background: #fff;
  padding: 20px;
  color: #000;
}

::v-deep .ant-table-thead > tr > th {
  color: #000;
  font-weight: bold;
}

::v-deep .ant-table-tbody > tr > td {
  color: #000;
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}

.mapDiv {
  width: 100%;
  height: 500px;
}
</style>
